#include "device.h"
#include <unistd.h>
#include <time.h>
#include <pthread.h>

void *sensor_update(void *arg) {
    DeviceManager *sensor = (DeviceManager *)arg;
    if (sensor == NULL) {
        fprintf(stderr, "sensor_update: 无效的传感器指针\n");
        return NULL;
    }
    printf("开始更新传感器: %s (ID: %d, 类型: %d)\n", sensor->name, sensor->id, sensor->Type);

    // 设置线程可取消
    pthread_setcancelstate(PTHREAD_CANCEL_ENABLE, NULL);
    pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, NULL);

    while (1) {
        printf("传感器: %s 更新\n", sensor->name);
        sensor->value = (float)(rand() % 100);  // 模拟 0-99 的随机值
        time_change(sensor);  // 记录传感器变化

        // 根据传感器类型控制执行器
        DeviceManager *actuator = NULL;
        if (sensor->Type == SENSOR_TEMP) {
            actuator = find_device_by_type(ACTUATOR_AC);
            if (actuator) {
                actuator->value = (sensor->value > 30.0 || sensor->value < 10.0) ? 1.0 : 0.0;
                time_change(actuator);
            }
        } else if (sensor->Type == SENSOR_HUMIDITY) {
            actuator = find_device_by_type(ACTUATOR_HUMIDIFI);
            if (actuator) {
                actuator->value = (sensor->value < 40.0) ? 1.0 : 0.0;
                time_change(actuator);
            }
        } else if (sensor->Type == SENSOR_LIGHT) {
            actuator = find_device_by_type(ACTUATOR_LIGHT);
            if (actuator) {
                actuator->value = (sensor->value < 20.0) ? 1.0 : 0.0;
                time_change(actuator);
            }
        }

        usleep(500000);  // 0.5 秒延迟
        pthread_testcancel();  // 线程取消点
    }

    printf("传感器更新完成: %s\n", sensor->name);  // 不会执行（死循环）
    return NULL;
}